<?php
/**
 * Manages storage, retrieval and deletion of library items.
 */
class DocCentre_Library
{
	/**
	 * Reference to the DocCentre system object.
	 * 
	 * @var DocCentre
	 */
	protected $system;
	
	/**
	 * Container for errors that occur during processing.
	 * 
	 * @var array
	 */
	public $errors = array();
	
	
	
	/**
	 * Builds the library manager object.
	 * 
	 * @param DocCentre $system
	 * @return DocCentre_Library
	 */
	public function __construct(DocCentre $system)
	{
		$this->system = $system;
	}
	
	
	/**
	 * Attempts to add the document. $fileref should be the key used to reference
	 * the uploaded file within the $_FILES superglobal.
	 * 
	 * @param string $fileref
	 * @param array $attributes = null
	 * @return bool
	 */
	public function add_document($fileref, array $attributes = null)
	{
		// Safety
		if (!current_user_can('upload_files'))
		{
			$this->errors[] = 'Insufficient permissions! Current user may not upload files.';
			return false;
		}
		
		// Attempt to upload the file
		$this->prepare_for_file_upload();
		$post = media_handle_upload($fileref, 0, array('post_status' => 'private'));
		
		// If successful, a post ID (positive integer) will be returned
		if (is_int($post) and $post > 0) 
		{
			add_post_meta($post, 'doccentre_file', array());
			return true;
		}
		// Most problems should result in a WP Errors object
		elseif (is_a($post, 'WP_Error'))
		{
			$this->errors[] = $post->errors['upload_error'][0];
			return false;
		}
		
		// Should a problem slip through the gaps, return false
		else return false;
	}
	
	
	/**
	 * Ensures that the necessary WordPress functions for handling and
	 * storing files are loaded.
	 */
	protected function prepare_for_file_upload()
	{
		if (!is_admin() or !function_exists('media_handle_upload'))
		{
			// Relevant functions are defined in the admin includes dir
			require trailingslashit(ABSPATH).'wp-admin/includes/file.php';
			require trailingslashit(ABSPATH).'wp-admin/includes/image.php';
			require trailingslashit(ABSPATH).'wp-admin/includes/media.php';
		}
	}
	
	
	/**
	 * Retrieves a list of all Document Centre documents. Optionally an
	 * array of WP_Query arguments can be passed to override the default
	 * behaviour.
	 * 
	 * @param array $query_args = null
	 * @return array
	 */
	public function list_documents(array $query_args = null)
	{
		// Default arguments
		$args = array(
			'meta_key' => 'doccentre_file',
			'nopaging' => true,
			'order' => 'DESC',
			'orderby' => 'date',
			'post_type' => 'attachment'
		);

		// Allow other plugins/theme code to modify the params also then build the query
		$args = apply_filters('doccentre_list_query', array_merge($args, (array) $query_args));
		$query = new WP_Query($args);
		$docs = array(); // Container
		
		// Loop through the query results
		while ($query->have_posts())
		{
			$query->the_post();
			$post = $query->post;
			
			$docs[] = array(
				'id' => $post->ID,
				'name' => $post->post_title,
				'server_url' => $this->system->server->form_access_url($post->ID)
			);
		}

		// Reset post data and return docs array
		wp_reset_postdata();
		return $docs;
	}
	
	
	/**
	 * Tests to see if the string is empty or effectively empty (ie
	 * if it contains whitespace only).
	 * 
	 * @param string $string
	 * @return bool
	 */
	protected function is_blank($string)
	{
		$string = trim((string) $string);
		return empty($string);
	}
	
}